<?php
/**
 * @package general
 */
class MemberGridFieldStatusAction implements GridField_ColumnProvider, GridField_ActionProvider {
    public function augmentColumns($gridField, &$columns) {
        if(!in_array('Actions', $columns)) {
            $columns[] = 'Actions';
        }
    }

    public function getColumnAttributes($gridField, $record, $columnName) {
        return array('class' => 'col-buttons');
    }

    public function getColumnMetadata($gridField, $columnName) {
        if($columnName == 'Actions') {
            return array('title' => '');
        }
    }

    public function getColumnsHandled($gridField) {
        return array('Actions');
    }

    public function getColumnContent($gridField, $record, $columnName) {
    	Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
		Requirements::javascript(FRAMEWORK_DIR . '/javascript/i18n.js');
		Requirements::add_i18n_javascript('general/javascript/lang');
    	Requirements::javascript('general/javascript/MemberGridFieldStatusAction.js');
    	Requirements::css('general/css/MemberGridFieldStatusAction.css');
        if($record->canEdit()) {
        	if($record->Status == 'Suspend'){
        		$field = GridField_FormAction::create($gridField, 'Active' . $record->ID, false, "active", array('RecordID' => $record->ID))->addExtraClass('gridfield-button-active')->setAttribute('title', _t('MemberGridFieldStatusAction.BUTTONACTIVE', 'Active'))->setAttribute('data-icon', 'accept')->setDescription(_t('MemberGridFieldStatusAction.ACTIVE_MEMBER', 'Active Member'));
			}
			else{
            	$field = GridField_FormAction::create($gridField, 'Suspend' . $record->ID, false, "suspend", array('RecordID' => $record->ID))->addExtraClass('gridfield-button-suspend')->setAttribute('title', _t('MemberGridFieldStatusAction.BUTTONSUSPEND', 'Suspend'))->setAttribute('data-icon', 'minus-circle')->setDescription(_t('MemberGridFieldStatusAction.SUSPEND_MEMBER', 'Suspend Member'));
			}
			
			return $field->Field();
        }
    }

    public function getActions($gridField) {
        return array(
            'active',
            'suspend'
        );
    }

    public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
        if($actionName == 'active' || $actionName = 'suspend') {
            $item = $gridField->getList()->byID($arguments['RecordID']);
            if(!$item) {
                return;
            }
			
			if(!$item->canEdit()){
				throw new ValidationException(_t('MemberGridFieldStatusAction.ACTION_PERMISSION', 'No permission to perform action for these item'), 0);
			}
			else{
	            if($actionName == 'active') {
	                $item->Status = 'Active';
	            	$item->write();
	            }
				
	            if($actionName == 'suspend') {
	                $item->Status = 'Suspend';
	            	$item->write();
	            }
			}
        }
    }
}
